package com.blog.controller;

import com.blog.response.Result;
import com.blog.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/upload")
public class UploadController {

    @Value("${config.ldir}")
    String ldir;

    @Value("${config.wdir}")
    String wdir;

    @Autowired
    private IdWorker idWorker;

    @PostMapping("/file")
    public Result upload(@RequestParam("upload") MultipartFile upload) throws Exception {
        // 上传的位置
        String path = System.getProperty("os.name").toLowerCase().indexOf("win") >= 0 ? wdir : ldir;
        // 按日期生成相对路径
        Calendar calendar = Calendar.getInstance();
        int year = calendar.getWeekYear();// 年
        String datePath = "meeting/" + Calendar.YEAR + "/" + Calendar.MARCH + "/" + Calendar.DAY_OF_MONTH + "/";
        String p = path + datePath;
        File file = new File(p);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 获取上传文件项
        String oriName = upload.getOriginalFilename();
        String extName = oriName.substring(oriName.lastIndexOf("."));
        // 修改文件名
        String uuidFileName = UUID.randomUUID().toString().replace("-", "");
        // 新文件名
        // String filename = uuidFileName + "-" + oriName;
        String newFilename = uuidFileName + extName;
        // 完成上传
        upload.transferTo(new File(p, newFilename));

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("path", datePath + newFilename);
        map.put("fileName", oriName);
        return new Result(200, "成功", map);
    }
}
